<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :ok-button-props="{ props: { disabled: this.showable } }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <form-tools
          ref="formTools"
          :formObj="formObj"
        >
        </form-tools>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import formTools from '@/components/BizTools/FormTools'
import pick from 'lodash.pick'
import { formObj } from './template'
import { FormMixin } from '@/mixins/FormMixin'
import { getObj, addObj, putObj } from '@/api/message/template'
export default {
  name: 'Form',
  mixins: [FormMixin],
  components: {
    formTools
  },
  data () {
    return {
      formObj,
      form: this.$form.createForm(this),
      confirmLoading: false
    }
  },
  methods: {
    edit (id, type) {
      this.visible = true
      const { form: { setFieldsValue, resetFields } } = this
      if (['edit', 'show'].includes(type)) {
        this.confirmLoading = true
        getObj(id).then(res => {
          const record = res.data
          this.confirmLoading = false
          this.$nextTick(() => {
            const item = this.formObj.columns.map(item => {
              return item.value
            })
            setFieldsValue(pick(record, item))
          })
        })
      } else {
        resetFields()
      }
    },
    handleOk () {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.confirmLoading = true
          try {
            if (this.type === 'add') {
              await addObj(values)
            } else if (this.type === 'edit') {
              await putObj(values)
            }
            setTimeout(() => {
              this.confirmLoading = false
              this.$emit('ok')
              this.visible = false
            }, 1500)
          } catch (e) {
            this.$message.error(e.msg)
            this.confirmLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
